﻿using System;
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace AVO
{
    public static class Extensions
    {
        public static IEnumerable<string> ExecuteScript(this string script, 
            string functionName,
            HttpContext httpContext, 
            SPContext spContext, 
            SPContentType ContentType,
            SPField Field,
            ListFieldIterator Iterator)
        {
            Dictionary<string, object> props = new Dictionary<string, object>();
            props.Add("httpContext", httpContext);
            props.Add("spContext", spContext);
            props.Add("ContentType", ContentType);
            props.Add("Field", Field);
            props.Add("Iterator", Iterator);
            props.Add("FormMode", spContext.FormContext.FormMode);
            return script.ExecuteScript(functionName, props);
        }

        public static IEnumerable<string> ExecuteScript(this string script, string command, Dictionary<string,object> parameters)
        {
            List<string> ret = new List<string>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.Open();

                    foreach (var kvp in parameters)
                        runspace.SessionStateProxy.SetVariable(kvp.Key, kvp.Value);

                    Pipeline pipe = runspace.CreatePipeline(script);

                    var psObjects = pipe.Invoke();

                    foreach (var o in psObjects)
                        ret.Add(o == null ? string.Empty : Convert.ToString(o.BaseObject));
                }
            });
            return ret;
        }
    }
}
